package com.wsh.crawler.controller;


import com.wsh.crawler.constant.NewsSourceEnum;
import com.wsh.crawler.entity.CommonPage;
import com.wsh.crawler.entity.News;
import com.wsh.crawler.entity.R;
import com.wsh.crawler.service.CrawlerService;
import com.wsh.crawler.service.NewsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.Positive;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;


@RestController
@Tag(name = "NewsController", description = "数据接口")
@RequestMapping("/api/v1")
public class NewsController {

    @Value("${remote.auth.token}")
    private String token;

    @Resource
    private NewsService newsService;

    @Resource
    private CrawlerService crawlerService;

    @GetMapping("/news")
    @Operation(summary = "爬虫资讯列表")
    @Parameters({
            @Parameter(name = "updated_at", description = "更新时间(秒级时间戳)条件：获取该时间之后更新的所有数据，不为时获取所有数据"),
            @Parameter(name = "page_num", description = "页码", example = "1"),
            @Parameter(name = "page_size", description = "页数", example = "10")
    })
    public R<CommonPage<News>> getNews(@RequestHeader("token") String token,
                                       @RequestParam(value = "updated_at", required = false) Long updatedAt,
                                       @Positive @RequestParam(value = "page_num", defaultValue = "1") Integer pageNum,
                                       @Positive @RequestParam(value = "page_size", defaultValue = "10") Integer pageSize) {

        if (!token.equals(this.token)) {
            return R.fail("无权限查看");
        }

        CommonPage<News> newsPage = newsService.getNewsList(updatedAt, pageNum, pageSize);
        return R.ok(newsPage);
    }

    @PostMapping("/news/{type}")
    @Operation(summary = "爬资讯")
    @Parameters({
            @Parameter(name = "type", description = "All（所有）、FlashScore、Premier League、La Liga、Bundesliga、Serie A、Ligue 1")
    })
    public R<Void> crawlNews(@PathVariable(value = "type", required = false) String type) {
        if ("All".equals(type)) {
            crawlerService.crawlAllSources();
        } else {
            crawlerService.crawlNews(NewsSourceEnum.fromName(type));
        }
        return R.ok();
    }

}